package com.baizw.cultivation.config;

import com.baizw.cultivation.enums.StatusEnum;
import com.baizw.cultivation.util.ShiroUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Date;

/**
 * MybatisPlus 配置
 *
 * @author 剧终1204
 * @version V1.0
 * @date 2020年04月27日 11:31
 */
@Configuration
@EnableTransactionManagement
@MapperScan({"com.baizw.cultivation.module.*.mapper", "com.baizw.cultivation.common.annotation.method"})
public class MybatisPlusConfig implements MetaObjectHandler {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer() {
        return builder -> builder.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        this.fillStrategy(metaObject, "createTime", new Date());
        this.fillStrategy(metaObject, "creatorId", ShiroUtil.getUser().getId());
        this.fillStrategy(metaObject, "status", StatusEnum.NORMAL);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.fillStrategy(metaObject, "updateTime", new Date());
        this.fillStrategy(metaObject, "updaterId", ShiroUtil.getUser().getId());
    }
}
